package tms.business.notification;

import tms.model.login.UserEntity;
import tms.persistence.time.TimeProvider;
import tms.util.activity.UserActivityManager;

import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.Stateless;
import javax.inject.Inject;
import java.util.Date;
import java.util.List;


@Stateless
public class NotificationTrigger {
    @Inject @NotifyBy(NotificationMethod.EMAIL)
    private NotificationBroker emailNotificationBroker;

    @Inject @NotifyBy(NotificationMethod.JABBER)
    private NotificationBroker jabberNotificationBroker;

    @Inject
    private UserActivityManager userActivityManager;

    @EJB
    TimeProvider timeProvider;


    @Schedule(second = "*/30", minute="*", hour="*")
    public void trigger() {
        List<UserEntity> users = timeProvider.getUnnotifiedUsersWithWorkDayEnded(new Date());
        if (!users.isEmpty()) {
            resetActivity(users);
            emailNotificationBroker.notifyUsers(users);
            jabberNotificationBroker.notifyUsers(users);
        }
    }

    /**
     *  Method simulates users activity to reset activity time to current time.
     * 
     * @param users
     */
    private void resetActivity(List<UserEntity> users) {
        for (UserEntity user : users) {
            userActivityManager.userActive(user.getId());
        }
    }
}
